<template>
  <div class="dialog-box" style="position: relative;">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditFormProjectRef"
        :model="formData"
        :size="defaultFormItemSize"
        :rules="rules"
        label-width="120px"
        label-position="right"
        @submit.native.prevent
      >
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="项目名称" prop="Project.projectName">
              <el-input
                class="input-item"
                v-model="formData.Project.projectName"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="坐标系">
              <el-select v-model="formData.Project.sourceCoordinateSystem" placeholder="请选择坐标系" style="width:100%">
                <el-option
                  v-for="(item, index) in coordinateSystems"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所在地区" prop="Project.areaCode">
              <el-cascader class="input-item" v-model="areaCodeDropdown.value" :clearable="true"
                           placeholder="所在地区" :loading="areaCodeDropdown.impl.loading" :props="{value: 'id', label: 'name', checkStrictly: true}"
                           @visible-change="onAreaCodeVisibleChange" :options="areaCodeDropdown.impl.dropdownList"
                           @change="onAreaCodeValueChange">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="项目年份" prop="Project.pjYear">
              <el-date-picker
                v-model="formData.Project.pjYear"
                type="year"
                format="yyyy"
                value-format="yyyy"
                placeholder="选择年">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-scrollbar>
    <el-row class="footer-box" type="flex" justify="end" align="middle">
      <el-button :size="defaultFormItemSize" @click="onCancel()">取消</el-button>
      <el-button :size="defaultFormItemSize" type="primary" @click="onSubmitFormProjectClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script>
import rules from '@/utils/validate';
import { stringCase, treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode } from '@/utils';
import { uploadMixin, statsDateRangeMixin, cachePageMixin } from '@/core/mixins';
import { DropdownWidget, TableWidget, UploadWidget, ChartWidget } from '@/utils/widget.js';
import { ProjectDbfilesController, ProjectController, ProjectTemplateController, MdbTableFieldController, DictionaryController } from '@/api';
import { AreaCodeController } from '@/api';

import coordinateSystems from '@/views/pipelineManage/coordinateSystem';

export default {
  name: 'formEditFormProject',
  props: {
    projectId: {
      default: undefined
    },
    subPage: {
      type: [Number, String, Boolean],
      default: 0
    },
    saveOnSubmit: {
      type: Boolean,
      default: true
    },
    rowData: {
      type: Object
    }
  },
  mixins: [uploadMixin, statsDateRangeMixin, cachePageMixin],
  data() {
    return {
      coordinateSystems,
      areaTreeData: [],
      areaCodeDropdown: {
        impl: new DropdownWidget(this.loadAreaCodeDropdownList, true, 'id'),
        value: []
      },
      formData: {
        Project: {
          // 项目ID
          projectId: undefined,
          // 项目名称
          projectName: undefined,
          // 坐标系
          sourceCoordinateSystem: "EPSG:4549",
          // 对应的项目模板
          templateId: undefined,
          // 所在地区编码
          areaCode: undefined,
          // 所在地区名称
          areaName: undefined,
          // 状态
          status: undefined,
          // 图片路径
          imageDirectory: undefined,
          // 项目年份
          pjYear: undefined,
          isDatasourceInit: false
        }
      },
      formEditFormProject: {
        isInit: false
      },
      rules: {
        'Project.coordinateSystem': [
          {required: true, message: '请输入坐标系', trigger: 'blur'}
        ],
        'Project.projectName': [
          {required: true, message: '请输入项目名称', trigger: 'blur'}
        ],
        'Project.pjYear': [
        ],
        'Project.areaCode': [
        ]
      },
    };
  },
  methods: {
    onCancel(isSuccess = false, data = null) {
      if (this.observer != null) {
        this.observer.cancel(isSuccess, data);
      }
    },
    /**
     * 重置过滤值
     */
    resetFormEditFormProject() {
      this.refreshFormEditFormProject();
    },
    /**
     * 重置所有过滤值
     */
    resetFilter () {
      this.resetFormEditFormProject();
    },
    /**
     */
    onAreaCodeVisibleChange (show) {
      this.areaCodeDropdown.impl.onVisibleChange(show).catch(e => {});
    },
    /**
     */
    onAreaCodeValueChange (value) {
    },
    /**
     * 保存
     */
    onSubmitFormProjectClick() {
      this.$refs.formEditFormProjectRef.validate((valid) => {
        if (!valid) return;
        // 级联操作
        if (!this.saveOnSubmit) {
          let formData = {
            ...this.formData.Project
          };
          this.onCancel(true, formData);
          return;
        }
        let areaCode = Array.isArray(this.areaCodeDropdown.value) ? this.areaCodeDropdown.value[this.areaCodeDropdown.value.length - 1] : undefined;
        let params = {
          projectDto: {
            projectId: this.formData.Project.projectId,
            pjYear: this.formData.Project.pjYear,
            projectName: this.formData.Project.projectName,
            sourceCoordinateSystem: this.formData.Project.sourceCoordinateSystem,
            areaCode: areaCode,
          }
        };

        let httpCall = this.isEdit ? ProjectController.update : ProjectController.add;
        httpCall(this, params).then(res => {
          this.$message.success('保存成功');
          this.onCancel(true);
        }).catch(e => {});
      });
    },
    loadProjectData() {
      return new Promise((resolve, reject) => {
        if (!this.isEdit) {
          resolve();
          return;
        }
        if (!this.saveOnSubmit && this.rowData != null) {
          this.formData.Project = JSON.parse(JSON.stringify(this.rowData));
          resolve();
          return;
        }
        let params = {
          projectId: this.projectId
        };
        ProjectController.view(this, params).then(res => {
          this.formData.Project = {...res.data, isDatasourceInit: true};
          if (this.formData.Project.projectTemplate == null) {
            this.$set(this.formData.Project, 'projectTemplate', {
              id: undefined,
              name: undefined,
              description: undefined,
              isDefault: undefined
            });
          }
          if (this.formData.Project.projectDbfiles == null) {
            this.$set(this.formData.Project, 'projectDbfiles', {
              projectId: undefined,
              mdbFile: undefined,
              sqliteFile: undefined,
              isDeleted: undefined
            });
          }
          resolve();
        }).catch(e => {
          reject(e);
        });
      });
    },
    onUploadError (e, file, fileList) {
      this.$message.error('文件上传失败');
    },
    onUploadLimit (files, fileList) {
      this.$message.error('已经超出最大上传个数限制');
    },
    refreshFormEditFormProject(reloadData = false) {
      this.areaCodeDropdown.impl.onVisibleChange(true).then(res => {
        if (!this.formEditFormProject.isInit) {
          this.areaCodeDropdown.value = findTreeNodePath(
            this.areaCodeDropdown.impl.dropdownList, this.formData.Project.areaCode, 'id');
        }
        this.formEditFormProject.isInit = true;
      });
    },
    loadAreaCodeDropdownList() {
      return new Promise((resolve, reject) => {
        let params = {};
        DictionaryController.dictAreaCode(this, params).then(res => {
          resolve(res.getList());
        }).catch(e => {
          reject(e);
        });
      });
    },
    formInit() {
      this.loadProjectData().then(res => {
        if (this.isEdit) this.refreshFormEditFormProject();
      }).catch(e => {});
    }
  },
  computed: {
    isEdit() {
      return this.saveOnSubmit ? this.projectId != null : this.rowData != null;
    }
  },
  mounted() {
    // 初始化页面数据
    this.formInit();
  }
};
</script>
